#!/usr/bin/env python3
"""
项目环境验证和测试脚本
"""

import sys
import subprocess
import importlib

def check_package(package_name, version_check=None):
    """检查包是否安装"""
    try:
        module = importlib.import_module(package_name)
        if version_check:
            version = getattr(module, '__version__', '未知')
            print(f"✓ {package_name} 已安装 (版本: {version})")
        else:
            print(f"✓ {package_name} 已安装")
        return True
    except ImportError:
        print(f"✗ {package_name} 未安装")
        return False

def check_environment_variables():
    """检查环境变量"""
    import os
    from dotenv import load_dotenv
    
    load_dotenv()
    
    required_vars = ['ZHIPU_API_KEY']
    missing_vars = []
    
    for var in required_vars:
        if not os.getenv(var):
            missing_vars.append(var)
            print(f"✗ 环境变量 {var} 未设置")
        else:
            print(f"✓ 环境变量 {var} 已设置")
    
    return len(missing_vars) == 0

def test_baidu_search():
    """测试百度搜索功能"""
    try:
        from tools.search_tools import BaiduSearchTool
        
        search_tool = BaiduSearchTool()
        result = search_tool.search("糖尿病预防", 3)
        
        if "失败" not in result and "错误" not in result:
            print("✓ 百度搜索功能正常")
            return True
        else:
            print("✗ 百度搜索功能异常")
            return False
            
    except Exception as e:
        print(f"✗ 百度搜索测试失败: {e}")
        return False

def test_zhipu_ai():
    """测试智谱AI功能"""
    try:
        from llm_zhipu import ZhipuAILLM
        
        llm = ZhipuAILLM()
        response = llm._call("你好，请用一句话回复")
        
        # 检查是否返回了有效响应（不是错误信息）
        if "调用失败" not in response and "错误" not in response and len(response.strip()) > 0:
            print(f"✓ 智谱AI功能正常，响应: {response[:50]}...")
            return True
        else:
            print(f"✗ 智谱AI功能异常: {response}")
            return False
            
    except Exception as e:
        print(f"✗ 智谱AI测试失败: {e}")
        return False

def main():
    print("=" * 50)
    print("LangChain项目环境验证")
    print("=" * 50)
    
    # 检查依赖包
    print("\n1. 检查依赖包:")
    packages = [
        ('langchain', True),
        ('langchain_community', True),
        ('zhipuai', True),
        ('requests', False),
        ('bs4', False),
    ]
    
    all_packages_ok = True
    for package, check_version in packages:
        if not check_package(package.replace('-', '_'), check_version):
            all_packages_ok = False
    
    # 检查环境变量
    print("\n2. 检查环境变量:")
    env_ok = check_environment_variables()
    
    # 功能测试
    print("\n3. 功能测试:")
    search_ok = test_baidu_search()
    ai_ok = test_zhipu_ai()
    
    print("\n" + "=" * 50)
    print("验证结果汇总:")
    print(f"依赖包: {'✓ 全部正常' if all_packages_ok else '✗ 有问题'}")
    print(f"环境变量: {'✓ 全部正常' if env_ok else '✗ 有问题'}")
    print(f"百度搜索: {'✓ 正常' if search_ok else '✗ 异常'}")
    print(f"智谱AI: {'✓ 正常' if ai_ok else '✗ 异常'}")
    
    if all([all_packages_ok, env_ok, search_ok, ai_ok]):
        print("\n🎉 所有检查通过！项目可以正常运行。")
        print("运行命令: python agent_demo.py")
    else:
        print("\n❌ 存在一些问题，请根据上述提示进行修复。")
        sys.exit(1)

if __name__ == "__main__":
    main()